<template>
  <div class="upload-container">
    <el-button icon='el-icon-upload' size="mini" :style="{background:color,borderColor:color}"
               @click="dialogVisible=true" type="primary">上传图片
    </el-button>
    <el-dialog append-to-body :visible.sync="dialogVisible">
      <!-- <el-upload class="editor-slide-upload"
                 action="http://macro-oss.oss-cn-shenzhen.aliyuncs.com"
                 :data="dataObj"
                 :multiple="true"
                 :file-list="fileList"
                 :show-file-list="true"
                 list-type="picture-card"
                 :on-remove="handleRemove"
                 :on-success="handleSuccess"
                 :before-upload="beforeUpload">
        <el-button size="small" type="primary">点击上传</el-button> -->
        <el-upload class="editor-slide-upload"
                 action=""
                 :file-list="fileList"
                 list-type="picture-card"
                 :on-remove="handleRemove"
                 :on-success="handleSuccess"
                 :before-upload="beforeUpload"
                 :http-request="uploadSectionFile"
                 >
        <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </el-dialog>
  </div>
</template>

<script>
  import {policy} from '@/api/oss'
  import random_string from '@/utils/randomString'
  import {cos,cos_delete} from '@/utils/cos'

  export default {
    name: 'editorSlideUpload',
    props: {
      color: {
        type: String,
        default: '#1890ff'
      }
    },
    data() {
      return {
        dialogVisible: false,
        listObj: {},
        fileList: [],
        dataObj: {
          policy: '',
          signature: '',
          key: '',
          ossaccessKeyId: '',
          dir: '',
          host: ''
        }
      }
    },
    methods: {
      uploadSectionFile(params){
        var _self = this;
        console.log('执行自定义上传方法',params)
        var file = params.file;
        console.log('dx:',file.type,file.size / 1024)
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif';
        const isLt2M = file.size / 1024 < 500;
        if (!isJPG) {
          this.$message.error('上传图片只能是 jpg/png/gif 格式!');
          params.onError()
          return
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 500kb!');
          params.onError()
          return
        }
        let fileName = file.name;
        let cosFileNeme = "content_" + (new Date()).getTime() + '_' + random_string(6) + fileName.substring(fileName.lastIndexOf('.'));
         cos.putObject({
              Bucket: 'wx-1256614213', /* 必须 */
              Region: 'ap-shanghai',     /* 存储桶所在地域，必须字段 */
              Key: cosFileNeme,              /* 必须 */
              Body: file, // 上传文件对象
              onProgress: function(progressData) {
                let data = JSON.stringify(progressData)
                  console.log('打印上传返回结果：',data);
                  params.onProgress({ percent: progressData.percent * 100})
              }
          }, function(err, data) {
            console.log(err || data);
            if(data){
              console.log('上传成功')
              params.onSuccess({url:'http://'+data.Location})
            }else{
              console.log('上传失败')
              params.onError()
            }
          });
      },
      checkAllSuccess() {
        return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess)
      },
      handleSubmit() {
        const arr = Object.keys(this.listObj).map(v => this.listObj[v])
        if (!this.checkAllSuccess()) {
          this.$message('请等待所有图片上传成功 或 出现了网络问题，请刷新页面重新上传！')
          return
        }
        console.log('提交图片数据：',arr);
        this.$emit('successCBK', arr);
        this.listObj = {};
        this.fileList = [];
        this.dialogVisible = false;
      },
      handleSuccess(res, file) {
        const uid = file.uid;
        const objKeyArr = Object.keys(this.listObj)
        for (let i = 0, len = objKeyArr.length; i < len; i++) {
          if (this.listObj[objKeyArr[i]].uid === uid) {
            this.listObj[objKeyArr[i]].url = res.url;
            // this.listObj[objKeyArr[i]].url = this.dataObj.host + '/' + this.dataObj.dir + '/' + file.name;
            this.listObj[objKeyArr[i]].hasSuccess = true;
            console.log('上传成功，打印：',this.listObj[objKeyArr[i]])
            return
          }
        }
      },
      handleRemove(file) {
        const uid = file.uid;
        const objKeyArr = Object.keys(this.listObj);
        for (let i = 0, len = objKeyArr.length; i < len; i++) {
          if (this.listObj[objKeyArr[i]].uid === uid) {
            delete this.listObj[objKeyArr[i]];
            return
          }
        }
      },
      beforeUpload(file) {
        const _self = this
        const fileName = file.uid;
        this.listObj[fileName] = {};
        this.listObj[fileName] = {hasSuccess: false, uid: file.uid, width: this.width, height: this.height};
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .upload-container .editor-slide-upload{
    margin-bottom: 20px;
  }
</style>